package com.dhcc.bpm.modules.content.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dhcc.bpm.common.annotation.Log;
import com.dhcc.bpm.common.enums.BusinessType;
import com.dhcc.bpm.common.utils.DateUtils;
import com.dhcc.bpm.common.utils.EmailUtils;
import com.dhcc.bpm.common.utils.SafeHtmlUtils;
import com.dhcc.bpm.modules.content.entity.Notice;
import com.dhcc.bpm.modules.content.service.INoticesService;
import com.dhcc.bpm.modules.content.vo.NoticeVO;
import com.dhcc.bpm.modules.orga.service.IOrgaService;
import com.dhcc.bpm.modules.orga.vo.OrgaVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * @ClassName NoticesController
 * @Description  门户公告管理 控制器
 * @Author lijiacheng
 * @Date 2020/2/21 14:16
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 */

@RestController
@AllArgsConstructor
@NoArgsConstructor
@RequestMapping("bpm-content/notices")
@Api(value = "", tags = "接口")
public class NoticesController extends BladeController {
	@Autowired
	private INoticesService noticeService;
	@Autowired
	private IOrgaService orgaService;

	@Value("${bpm.message.title}")
	private String mailTitle;
	@Value("${bpm.approval.isSendMail}")
	private boolean isSendMail;
	/**
	 * 详情
	 */
	@ApiLog("公告信息模块表详情")
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入notice")
	public R<Notice> detail(Notice notice) {
		Notice detail = noticeService.getOne(Condition.getQueryWrapper(notice));
		return R.data(detail);
	}

	/**
	 * 分页 
	 */
	@ApiLog("公告信息模块表列表")
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入notice")
	public R<IPage<NoticeVO>> list(NoticeVO notice, Query query) {
		IPage<NoticeVO> pages = noticeService.selectNoticePage(Condition.getPage(query), notice);
		return R.data(pages);
	}

	/**
	 * 自定义分页 
	 */
	@ApiLog("公告信息模块表分页")
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入notice")
	public R<IPage<NoticeVO>> page(NoticeVO notice, Query query) {
		IPage<NoticeVO> pages = noticeService.selectNoticePage(Condition.getPage(query), notice);
		return R.data(pages);
	}

	/**
	 * 新增 
	 */
	@ApiLog("公告信息模块表新增")
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入notice")
	@Log(title = "公告信息新增", businessType = BusinessType.INSERT)
	public R save(@Valid @RequestBody Notice notice) {
		Date date = DateUtil.now();
		LocalDateTime now = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
		notice.setContentDate(DateUtils.asDate(LocalDateTime.now()));
		notice.setStatus(0);
		String safeHtml = SafeHtmlUtils.getSafeHtml(notice.getContent());
		notice.setContent(safeHtml);
		return R.status(noticeService.save(notice));
	}

	/**
	 * 修改 
	 */
	@ApiLog("公告信息模块表更新")
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入notice")
	@Log(title = "公告信息更新", businessType = BusinessType.UPDATE)
	public R update(@Valid @RequestBody Notice notice) {
		String safeHtml = SafeHtmlUtils.getSafeHtml(notice.getContent());
		notice.setContent(safeHtml);
		return R.status(noticeService.updateById(notice));
	}

	/**
	 * 新增或修改 
	 */
	@ApiLog("公告信息模块表提交")
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "公告上线或下线", notes = "传入notice")
	@Log(title = "公告信息", businessType = BusinessType.INSERT)
	public R submit(@Valid @RequestBody Notice notice) {
		Date date = DateUtil.now();
		LocalDateTime now = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
		notice.setContentDate(DateUtils.asDate(LocalDateTime.now()));
		if(isSendMail){
			if(noticeService.saveOrUpdate(notice)){
				if(notice.getStatus()==0){
					//公告下线，不需要发送邮件
					return R.status(true);
				}
				Notice notice1 = new Notice();
				notice1.setId(notice.getId());
				Notice detail = noticeService.getOne(Condition.getQueryWrapper(notice1));

				if(!"1".equals(detail.getNoticeType()) || detail.getOpcProductId()==null){
					//如果公告类型不需要通知机构或公告没有关联产品信息，就不需要发邮件
					return R.status(true);
				}
				List<OrgaVO> orgaList = orgaService.selectOrgaByProductId(detail.getOpcProductId());
				EmailUtils email = new EmailUtils();
				//邮件发送成功计数器
				int i = 0;
				//邮件发送失败计数器
				int j = 0;
				for (OrgaVO orga : orgaList) {
					if("".equals(orga.getOrgaEmail()) && orga.getOrgaEmail()!=null &&
							email.sendEmail(
									mailTitle,
									orga.getOrgaEmail(),
									mailTitle+"公告",
									detail.getContent())
					){
						i++;
					}else{
						j++;
					}
				}
				if(j==0){
					//全部发送成功
					return R.status(true);
				}else{
					return R.fail("共发送"+orgaList.size()+"条公告邮件，发送失败："+j+"条");
				}

			}else{
				return R.status(false);
			}
		}else{
			return R.status(noticeService.saveOrUpdate(notice));
		}


	}

	
	/**
	 * 删除 
	 */
	@ApiLog("公告信息模块表删除")
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "公告信息删除", notes = "传入ids")
	@Log(title = "接口权限", businessType = BusinessType.DELETE)
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(noticeService.deleteLogic(Func.toLongList(ids)));
	}

	
}
